Obafemi Emmanuel

Mastering React Router

Published 6 months ago

Introduction

React Router is a popular library for handling navigation in React applications. It allows developers to manage routes efficiently, enabling seamless navigation between different views of a single-page application (SPA). In this guide, we'll cover the fundamental aspects of React Router, including setting it up, navigating between pages, handling dynamic routes with URL parameters, and implementing redirects and navigation guards.


1. Setting Up React Router

Before using React Router, you need to install it. Open your terminal and run the following command:

npm install react-router-dom

Once installed, wrap your application with the BrowserRouter component, which enables routing capabilities.


Example Setup:

import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Home from './pages/Home';
import About from './pages/About';

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </Router>
  );
}

export default App;

Here, we define two routes: the home page (/) and the about page (/about). The Routes component ensures that only one route is rendered at a time.


2. Navigating Between Pages

React Router provides the Link component to navigate between pages without reloading the browser.


Example Navigation:

import { Link } from 'react-router-dom';

function Navbar() {
  return (
    <nav>
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/about">About</Link></li>
      </ul>
    </nav>
  );
}

Alternatively, you can use the useNavigate hook for programmatic navigation.


Example:

import { useNavigate } from 'react-router-dom';

function Home() {
  const navigate = useNavigate();

  const goToAbout = () => {
    navigate('/about');
  };

  return (
    <div>
      <h1>Home Page</h1>
      <button onClick={goToAbout}>Go to About</button>
    </div>
  );
}

3. Dynamic Routes & URL Parameters

Sometimes, we need to pass dynamic values via the URL. React Router allows this through URL parameters.


Setting Up a Dynamic Route:

<Route path="/user/:id" element={<UserProfile />} />

Here, :id is a dynamic parameter that can change based on user selection.


Accessing URL Parameters:

To retrieve the URL parameter, use the useParams hook.

import { useParams } from 'react-router-dom';

function UserProfile() {
  const { id } = useParams();
  return <h1>User Profile for ID: {id}</h1>;
}

If the user navigates to /user/123, the page will display "User Profile for ID: 123".


4. Redirects & Navigation Guards

Redirecting Users

React Router provides the Navigate component to redirect users programmatically.

import { Navigate } from 'react-router-dom';

function NotFound() {
  return <Navigate to="/" />;
}

This will automatically redirect users to the home page when they visit a non-existent route.


Implementing Navigation Guards

To protect certain routes, use authentication logic within a higher-order component.

import { Navigate } from 'react-router-dom';

function ProtectedRoute({ children }) {
  const isAuthenticated = false; // Example condition
  return isAuthenticated ? children : <Navigate to="/login" />;
}

Usage:

<Route path="/dashboard" element={<ProtectedRoute><Dashboard /></ProtectedRoute>} />

If the user is not authenticated, they will be redirected to the login page.


Conclusion

React Router simplifies navigation in React applications, providing powerful tools for handling routes dynamically and securely. By mastering the concepts of setting up React Router, navigating between pages, handling dynamic parameters, and implementing redirects and navigation guards, you can build seamless and user-friendly web applications.

Happy coding!


Leave a Comment


Choose Colour